package mv.crawler;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import mv.io.BluetoothIO;
import mv.io.FileIO;
import mv.main.MObject;
import mv.wap.Link;
import mv.wap.ListLayout;
import mv.wap.Page;
import mv.wap.Paragraph;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Class description...
 *
 * @author mvu
 */
public class FeedCrawler extends MObject {
  public List<Page> crawl() throws Exception {
    String[] tags = new String[]{"milpitas", "fremont", "sanjose", "shortsale"};
    List<Page> pages = new ArrayList<Page>();
    Page home = new Page("tosee");
    ListLayout listLayout = new ListLayout();
    home.addElement(listLayout);
    pages.add(home);
    for (String tag : tags) {
      Page page = createPageForTags("tosee+" + tag);
      page.addElement(new Link(home));
      listLayout.addElement(new Link(page));
      pages.add(page);
    }
    return pages;
  }

  private Page createPageForTags(String tags) throws Exception {
    URL feedUrl = new URL(getDeliciousURL(tags));
    SyndFeedInput input = new SyndFeedInput();
    SyndFeed feed = input.build(new XmlReader(feedUrl));
    Page page = new Page(tags);
    for (Object entry : feed.getEntries()) {
      SyndEntryImpl syndEntry = (SyndEntryImpl) entry;
      String title = syndEntry.getTitle();
      SyndContent description = syndEntry.getDescription();
      syndEntry.getUpdatedDate();
      StringBuilder text = new StringBuilder();
      if (description != null) {
        text.append("<font color=\"red\">")
                .append(description.getValue())
                .append("</font> ");
      }
      text.append(syndEntry.getPublishedDate());
      page.addElement(new Paragraph(title, text.toString()));
    }
    return page;
  }

  private String getDeliciousURL(String tags) {
    return "http://feeds.delicious.com/v2/rss/vqminh/" + tags + "?count=30";
  }

  public static void main(String[] args) throws Exception {
    List<Page> pages = new FeedCrawler().crawl();
    FileIO.getInstance().save(pages);
    BluetoothIO.main(new String[0]);
  }

}
